<template>
  <div>
    <div class="search">
      <el-form
        :inline="true"
        :model="tableData"
        ref="ShouyeFormRef"
        class="demo-form-inline"
      >
        <!--输入并查询项目名称-->
        <el-form-item label="项目名称" style="margin-left: 10px">
          <!-- <el-select v-model="projectName" placeholder="请选择">
            <el-option
              v-for="item in tableData"
              :key="item.projectId"
              :label="item.projectName"
              :value="item.projectName"
            >
            </el-option>
          </el-select> -->
          <el-input
            v-model="projectName"
            placeholder="请输入项目名称"
          ></el-input>
        </el-form-item>

        <!--输入并查询项目阶段-->
        <el-form-item label="项目阶段" style="margin-left: 10px">
          <!-- <el-select v-model="projectPhase" placeholder="请选择">
            <el-option
              v-for="item in tableData"
              :key="item.projectId"
              :label="item.projectPhase"
              :value="item.projectPhase"
            >
            </el-option>
          </el-select> -->
          <el-input
            v-model="projectPhase"
            placeholder="请输入项目阶段"
          ></el-input>
        </el-form-item>

        <!--输入并查询业主名称-->
        <el-form-item label="业主名称" style="margin-left: 10px">
          <el-input v-model="ownerName" placeholder="请输入"></el-input>
        </el-form-item>

        <!--输入并查询项目是否派工-->
        <el-form-item label="是否派工" style="margin-left: 10px">
          <el-select v-model="dispatch" placeholder="请选择">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>

        <!--重置和查询按钮-->
        <el-form-item>
          <el-button type="info" plain @click="load(1)">查询</el-button>
          <el-button type="warning" plain @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--新增与删除操作按钮-->

    <div class="operation">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <!--      <el-button type="danger" plain @click="delBatch" style="margin-left: 10px"-->
      <!--      >批量删除</el-button-->
      <!--      >-->
    </div>

    <!--项目表-->

    <div class="table">
      <el-table
        :data="tableData"
        strip border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="projectId"
          label="序号"
          width="70"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column prop="projectName" label="项目名称">
          <template slot-scope="scope">
            <el-link type="primary" plain @click="toDetail(scope.row)">{{
              scope.row.projectName
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="projectCategory"
          label="项目类别"
        ></el-table-column>
        <el-table-column prop="projectPhase" label="项目阶段"></el-table-column>
        <el-table-column prop="dispatch" label="是否派工"></el-table-column>
        <el-table-column
          prop="projectBegin"
          label="项目开始时间"
        ></el-table-column>
        <el-table-column
          prop="projectEnd"
          label="项目结束时间"
        ></el-table-column>
        <el-table-column prop="ownerName" label="业主名称"></el-table-column>
        <el-table-column prop="ownerContact" label="联系方式"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="primary"
              plain
              @click="toDetail(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              plain
              @click="del(scope.row.projectId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import Child from "@/views/manager/ProjectChild.vue";
export default {
  name: "Project",
  components: { Child },
  data() {
    return {
      options: [],
      formInline: {
        username: "",
        region: "",
        project: "",
        protime: "",
      },
      input: "",
      projectName: "",
      dispatch: "",
      ownerName: "",
      projectPhase: "",
      tableData: [], // 所有的数据
      pageNum: 1, // 当前的页码
      pageSize: 10, // 每页显示的个数
      total: 0,
      username: null,
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
      },

      myId: "123",
      ids: [],
      departmentData: [],
    };
  },

  created() {
    this.load(1);
    this.loadDepartments();
  },
  methods: {
    generateRandomData() {
      // 模拟生成随机表格数据
      const randomData = [];
      for (let i = 0; i < 20; i++) {
        const row = {
          teamName: `班组${i + 1}`,
          contractor: `承包人${i + 1}`,
          contact: `联系方式${i + 1}`,
          numberOfWorkers: Math.floor(Math.random() * 100) + 1,
          remark: `备注${i + 1}`,
        };
        randomData.push(row);
      }
      this.tableData = randomData;
      this.totalItems = randomData.length;
    },
    calculateAttendanceStatus() {
      // 模拟生成随机考勤数据
      const randomAttendance = {};
      for (let i = 1; i <= this.daysInMonth; i++) {
        randomAttendance[i] = Math.random() < 0.8 ? "normal" : "abnormal"; // 80%正常，20%异常
      }
      this.attendanceStatus = randomAttendance;
    },
    handleDateChange() {
      // 当日期改变时重新计算考勤情况
      this.calculateAttendanceStatus();
    },

    //编辑按钮函数
    toDetail(row) {
      this.tableData = JSON.parse(JSON.stringify(row));
      this.$router.push({
        name: "ProjectChild",
        query: { param: this.tableData },
      });
    },
    loadDepartments() {
      this.$request.get("/projects").then((res) => {
        if (res.code === "200") {
          this.tableData = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    handleAdd() {
      // 新增数据
      this.tableData = {
        // projectId: 0,
        // projectName: "",
        // dispatch: 0,
        // ownerName: "",
        // projectPhase: "",
        // teamsId: 0,
        // unitId: 0,
        manifestList: [],
        total: this.total,
      }; // 新增数据的时候清空数据
      console.log(this.total);
      this.$router.push({
        name: "ProjectChild",
        query: { param: this.tableData },
      });
      //   this.fromVisible = true; // 打开弹窗
    },
    handleEdit(row) {
      // 编辑数据
      this.form = JSON.parse(JSON.stringify(row)); // 给form对象赋值  注意要深拷贝数据
      this.fromVisible = true; // 打开弹窗
    },
    save() {
      // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? "/projects/update" : "/projects/insert",
            method: this.form.id ? "PUT" : "POST",
            data: this.form,
          }).then((res) => {
            if (res.code === "200") {
              // 表示成功保存
              this.$message.success("保存成功");
              this.load(1);
              this.fromVisible = false;
            } else {
              this.$message.error(res.msg); // 弹出错误的信息
            }
          });
        }
      });
    },
    del(id) {
      // 单个删除
      this.$confirm("您确定删除吗？", "确认删除", { type: "warning" })
        .then((response) => {
          this.$request.delete("/projects/" + id).then((res) => {
            if (res.code === "200") {
              // 表示操作成功
              this.$message.success("操作成功");
              this.load(1);
            } else {
              this.$message.error(res.msg); // 弹出错误的信息
            }
          });
        })
        .catch(() => {});
    },
    handleSelectionChange(rows) {
      // 当前选中的所有的行数据
      this.ids = rows.map((v) => v.id);
    },
    // delBatch() {
    //   // 批量删除
    //   if (!this.ids.length) {
    //     this.$message.warning("请选择数据");
    //     return;
    //   }
    //   this.$confirm("您确定批量删除这些数据吗？", "确认删除", {
    //     type: "warning",
    //   })
    //       .then((response) => {
    //         this.$request
    //             .delete("/employee/delete/batch", { data: this.ids })
    //             .then((res) => {
    //               if (res.code === "200") {
    //                 // 表示操作成功
    //                 this.$message.success("操作成功");
    //                 this.load(1);
    //               } else {
    //                 this.$message.error(res.msg); // 弹出错误的信息
    //               }
    //             });
    //       })
    //       .catch(() => {});
    // },
    load(pageNum) {
      // 分页查询
      if (pageNum) this.pageNum = pageNum;
      this.$request
        .get("/projects", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            projectName: this.projectName,
            projectPhase: this.projectPhase,
            ownerName: this.ownerName,
            dispatch: this.dispatch,
          },
        })
        .then((res) => {
          this.tableData = res.data?.rows;
          this.total = res.data?.total;
        });
    },
    reset() {
      this.projectName = null;
      this.projectCategory = null;
      this.projectPhase = null;
      this.dispatch = null;
      this.load(1);
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum);
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把头像属性换成上传的图片的链接
      this.form.avatar = response.data;
    },
  },
};
</script>

<style scoped></style>
